<?php
/*
 * FeedUtil
 * https://developers.google.com/youtube/v3/docs/playlistItems/list
 * https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/youtube/my_uploads.php
 *   https://accounts.google.com/UpdateDomain
*/
require_once dirname(__FILE__) . '/../public/Google/Client.php';
require_once dirname(__FILE__) . '/../public/Google/Service/YouTube.php';

class FeedUtil
{
    const MAX_RESULTS = 25;
    const NO_DATA_FOUND = 0;
    const POS_PLAYLIST_ID = 1;
    const MAX_PER_PAGE = 25;
    const CRLF="\n";
    private $keyword;

        public function retrievePlaylists($oauth2_client_id, $oauth2_client_secret, $developerKey){

        if(!isset($_SESSION['token'])){
            return false;
        }

        $this->refresh_token();
        $client = new Google_Client();
        $client->setClientId($oauth2_client_id);
        $client->setClientSecret($oauth2_client_secret);
        $client->setDeveloperKey($developerKey); // API key
        $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . "/Index/oauth", FILTER_SANITIZE_URL);
        $client->setRedirectUri($redirect);
        $youtube = new Google_Service_YouTube($client);
        $htmlBody = "";

        if (isset($_SESSION['code'])){
            if (strval($_SESSION['state']) !== strval($_GET['state'])){
                die('The session state did not match.');
            }
            $client->authenticate();
            $_SESSION['token'] = $client->getAccessToken();
            header('Location: ' . $redirect);
        }

        if (isset($_SESSION['token'])){
            $client->setAccessToken($_SESSION['token']);
        }

        try{
            $playlists = $youtube->playlists->listPlaylists('snippet', array(
                'maxResults' => 50,
                'mine' => true,
                    ));
            $entriesFound = self::NO_DATA_FOUND;
            $playlistEntries = " <form id='navigationForm' action='javascript:void(0)'>";
            $playlistEntries .= "<select name='select-choice-min' id='select-choice-1' onchange='ytVideoApp.viewPlayListGrid(this.options[this.selectedIndex].value),null'>";
            foreach ((array)$playlists['items'] as $item)
            {
                $playlistTitle = $item['snippet']['title'];
                $feedUrl = "http://www.youtube.com/playlist?list=" . $item['id'];
                $playlistEntries .= "<option value=" . "'" . $feedUrl . "'" . " ";
                if(isset($_SESSION['feed_url'])){
                    if($_SESSION['feed_url']==$feedUrl){
                        $playlistEntries .= "selected";
                    }
               }
                $playlistEntries .=  " >" . $playlistTitle . "</option>";
                $entriesFound++;
            }
            $playlistEntries .="</select></form>";

            if ($entriesFound > self::NO_DATA_FOUND){
                $htmlBody = $playlistEntries;
            } else {
                print 'No playlists found';
            }
        }catch (Google_ServiceException $e){
            $htmlBody .= sprintf('<p>A service error retrievePlaylists 1: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
        }
        catch (Google_Exception $e){
            $htmlBody .= sprintf('<p>An client error occurred2 retrievePlaylists: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            echo "<a href='/Index/oauth?logout'>Login</a>";
        }
        $_SESSION['token'] = $client->getAccessToken();

        echo $htmlBody;
    }

    public function getPlaylists($oauth2_client_id, $oauth2_client_secret, $developerKey){
        if(!isset($_SESSION['token'])){
            return false;
        }
        $this->refresh_token();
        $client = new Google_Client();
        $client->setClientId($oauth2_client_id);
        $client->setClientSecret($oauth2_client_secret);
        $client->setDeveloperKey($developerKey); // API key
        $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . "/Index/oauth", FILTER_SANITIZE_URL);
        $client->setRedirectUri($redirect);
        $youtube = new Google_Service_Youtube($client);
        $htmlBody = "";
        if (isset($_SESSION['code'])){
            if (strval($_SESSION['state']) !== strval($_GET['state'])){
                die('The session state did not match.');
            }
            $client->authenticate();
            $_SESSION['token'] = $client->getAccessToken();
            header('Location: ' . $redirect);
        }
        if (isset($_SESSION['token'])){
            $client->setAccessToken($_SESSION['token']);
        }

        try{
            $playlists = $youtube->playlists->listPlaylists('snippet', array(
                'maxResults' => 50,
                'mine' => true,
                    ));
            
            return $playlists;
        }catch (Google_ServiceException $e){
            $htmlBody .= sprintf('<p>A service error retrievePlaylists 1: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
        }
        catch (Google_Exception $e){
            $htmlBody .= sprintf('<p>An client error occurred2 retrievePlaylists: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            echo "<a href='/Index/oauth?logout'>Login</a>";
        }
        $_SESSION['token'] = $client->getAccessToken();

        echo $htmlBody;
    }

    /*
     * feedsFromPlaylistOthers
     * 公開されている他人のプレイリストを取得します
     */
    public function feedsFromPlaylistOthers($feed_url, $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey)
    {
        $client = new Google_Client();
        $client->setDeveloperKey($developerKey);
        $youtube = new Google_Service_Youtube($client);
        $errors = array();
        $htmlBody = "";
        try
        {
            $uris = explode("list=", urldecode($feed_url));
            $playlistId = $uris[self::POS_PLAYLIST_ID];
            $pageToken = "";
            if (isset($_REQUEST['pageToken'])){
                $pageToken = $_REQUEST['pageToken'];
            }
            if (!empty($pageToken)){
                $playlistItems = $youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', array(
                    'maxResults' => self::MAX_RESULTS,
                    'playlistId' => $playlistId,
                    'pageToken' => $pageToken
                        ));
            }else{
                $playlistItems = $youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', array(
                    'maxResults' => self::MAX_RESULTS,
                    'playlistId' => $playlistId,
                        ));
            }
            if (empty($playlistItems)) {
                print 'No playlists found';
            }
        }catch (Google_ServiceException $e) {
            $htmlBody.= sprintf('<p>A service error occurred feedsFromPlaylistOthers: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            $errors['erros'] = $htmlBody;
            return $errors;
        }
        catch (Google_Exception $e)
        {
            $htmlBody.= sprintf('<p>An client error occurred feedsFromPlaylistOthers: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            $errors['erros'] = $htmlBody;
            return $errors;
        }
        return $playlistItems;
    }
/* see https://developers.google.com/youtube/v3/docs/search/list
 * 
 */
    public function feedsFromKeyword($keyword=null, $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey)
    {

        $client = new Google_Client();
        $client->setDeveloperKey($developerKey);
        $youtube = new Google_Service_Youtube($client);
        $errors = array();
        $htmlBody = "";

        try
        {

            if(!isset($keyword)){
                $keyword = "再生リスト";
            }else{
                $keyword = urldecode($keyword);
                $this->keyword=$keyword;
            }
            $type = "video";
            $get_order= 'rating';
            $pageToken = "";
            if (isset($_REQUEST['pageToken'])){
                $pageToken = $_REQUEST['pageToken'];
            }
            if (!empty($pageToken)){
                    $playlistItems = $youtube->search->listSearch('id,snippet', array(
                            'q' => $keyword,
                            'maxResults' => self::MAX_RESULTS,
                            'order' => '$get_order',
                            'type' => $type,
                            'pageToken' => $pageToken,
                            'order' => $get_order,
                ));
            }else{
                  $playlistItems = $youtube->search->listSearch('id,snippet', array(
                    'q' => $keyword,
                    'maxResults' => self::MAX_RESULTS,
                    'order' => '$get_order',
                    'type' => $type,
                    'order' => $get_order,
                  ));
            }
            if (empty($playlistItems)) {
                print 'No playlists found';
            }
        }catch (Google_ServiceException $e) {
            
            $htmlBody.= sprintf('<p>A service error  feedsFromPlaylistOthers1: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            $errors['erros'] = $htmlBody;
            return $errors;
        }
        catch (Google_Exception $e)
        {
            $htmlBody.= sprintf('<p>An client error feedsFromPlaylistOthers2: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            $errors['erros'] = $htmlBody;
            return $errors;
        }
        return $playlistItems;
    }


   public function getRandomVideoId($playlistItems){
        $video_ids = array();
        if(!isset($playlistItems["items"])){
            return "";
        }
         foreach ((array) $playlistItems["items"] as $playlistEntry){
             if (isset($playlistEntry["contentDetails"]["videoId"])){
                $video_ids[] =$playlistEntry["contentDetails"]["videoId"];
             }else if (isset($playlistEntry["id"]["videoId"])){
                $video_ids[] =$playlistEntry["id"]["videoId"]; 
             }
         }
         $counter= count($video_ids);
         $index = mt_rand(0,$counter-1);
        return $video_ids[$index];
    }
   public function feedToHtml($playlistItems,$is_smartphone =null)
    {
        $script_tag = "";
        $grid_tag = "";
        $video_ids = array();
        $video_titles = array();
        $options = array();
        foreach ((array) $playlistItems["items"] as $playlistEntry) {
            try{
                 if (isset($playlistEntry["contentDetails"]["videoId"])){
                    $video_id = $playlistEntry["contentDetails"]["videoId"];
                  }else if (isset($playlistEntry["id"]["videoId"])){
                      $video_id = $playlistEntry["id"]["videoId"];
                  }
                if (empty($video_id)){
                    continue;
                }
                if (!isset($playlistEntry["snippet"]["thumbnails"])){
                    continue;
                }
                require_once (APPLICATION_PATH . "/../library/UserAgentManager.class.php");
                $userAgentManager = new UserAgentManager();
                $is_smartphone = $userAgentManager->is_smartphone();
                $video_ids[] = $video_id;
                $video_titles[] = $playlistEntry["snippet"]["title"];
                $options[$video_id] = $playlistEntry["snippet"]["thumbnails"]["default"]["url"];
            if($is_smartphone){
				 $imageURL = $playlistEntry["snippet"]["thumbnails"]["small"]["url"];
            }else{
                $imageURL = $playlistEntry["snippet"]["thumbnails"]["medium"]["url"];
            }

                $title = htmlspecialchars($playlistEntry["snippet"]["title"], ENT_COMPAT, 'UTF-8');
//                $description = htmlspecialchars($playlistEntry["snippet"]["description"], ENT_COMPAT, 'UTF-8');
                $grid_tag = $grid_tag . "<div class='grid'>".self::CRLF;
                $grid_tag = $grid_tag . " <div class='imgholder'>".self::CRLF;
                $grid_tag = $grid_tag . "  <div class='gridimg' >".self::CRLF;
                $grid_tag = $grid_tag . "   <a href='#player' ";
                $grid_tag = $grid_tag .  " onclick=" . '"' . "loadVideoByVideoId('" . $video_id . "')" . '"';
                $grid_tag = $grid_tag ." >".self::CRLF;
                $grid_tag = $grid_tag . "<img src=" . "'" . $imageURL . "'";
                $grid_tag = $grid_tag . " alt=" . '"' . $title . '"' . " />";
                $grid_tag = $grid_tag ."</a>".self::CRLF;
//                $grid_tag = $grid_tag . "   <!--<div class='title'>" . $title . " </div>-->".self::CRLF;
//                $grid_tag = $grid_tag . "   <div class='description'>" . $description . " </div><!--description-->".self::CRLF;
                $grid_tag = $grid_tag . "  </div><!--gridimg-->".self::CRLF;
                $grid_tag = $grid_tag . "</div><!--imgholder-->".self::CRLF;
                $grid_tag = $grid_tag . "</div><!--grid-->".self::CRLF;
            }
            catch (Exception $exc)
            {
                //echo $exc->getTraceAsString();
                continue;
            }
        }

        $video_id_csv = implode(',', $video_ids);
        $script_tag = " <div ><form name='f2'><input type='hidden' name='csv_video_ids' value='" . $video_id_csv . "'/></form></div>";

        $pagingTag="";
        $jsMethodName="";
        $keyword="null";
        if( isset($_REQUEST['keyword'])){
            $jsMethodName="ytVideoApp.feeds_from_keyword";
            $keyword=$_REQUEST['keyword'];
        }else if(isset($_REQUEST['feed_url'])){
            $jsMethodName="ytVideoApp.viewPlayListGrid";
            $keyword="";
        }else if(isset($_SESSION['feed_url'])){
            $jsMethodName="ytVideoApp.viewPlayListGrid";
            $keyword="";
        }else if(isset($_SESSION['keyword'])){
          $jsMethodName="ytVideoApp.feeds_from_keyword";
            $keyword=$_SESSION['keyword'];    
        }else{
             $jsMethodName="ytVideoApp.feeds_from_keyword";
            $keyword=$this->keyword;
        }
        
        if (isset($playlistItems["prevPageToken"])){
            $pagingTag .= "<div class='paging'><a href=# onclick=" ."\"" . $jsMethodName ."('".$keyword ."'," . "'" . $playlistItems["prevPageToken"] ."');" . "\">| prev | </a></div>";
        }
        if (isset($playlistItems["nextPageToken"])){
            $pagingTag .= "<div class='paging'><a href=# onclick=" ."\"" . $jsMethodName ."('".$keyword ."'," . "'" . $playlistItems["nextPageToken"] . "');" . "\"> | next |</a></div>";
        }

        $totalResults = $playlistItems['pageInfo']['totalResults'].self::CRLF;
        $totalResultsTag  ="<div class='grid'>".self::CRLF;
        $totalResultsTag .="<div class='imgholder'>".self::CRLF;
        $totalResultsTag .="<div class='gridimg'><div class='totalResults'>" . "total:" . $totalResults . $pagingTag.self::CRLF;
        $totalResultsTag .="画像をクリックすると再生します</div><!--totalResults-->".self::CRLF;
        $totalResultsTag .="</div><!--gridimg-->".self::CRLF;
        $totalResultsTag .="</div><!--imgholder-->".self::CRLF;
        $totalResultsTag .="</div><!--grid-->".self::CRLF;
        //echo print_r($playlistItems);
        return $grid_tag . $script_tag . $totalResultsTag;
    }

    public function feeds_from_playlist($feed_url, $OAUTH2_CLIENT_ID, $OAUTH2_CLIENT_SECRET, $developerKey)
    {
        $this->refresh_token();
        $client = new Google_Client();
        $client->setClientId($OAUTH2_CLIENT_ID);
        $client->setClientSecret($OAUTH2_CLIENT_SECRET);
        $client->setDeveloperKey($developerKey); // API key
        $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . '/Index/oauth', FILTER_SANITIZE_URL);
        $client->setRedirectUri($redirect);
        $youtube = new Google_Service_Youtube($client);
        $htmlBody = "";

        if (isset($_GET['code']))
        {
            if (strval($_SESSION['state']) !== strval($_GET['state']))
            {
                die('The session state did not match.');
            }
            $client->authenticate();
            $_SESSION['token'] = $client->getAccessToken();
            header('Location: ' . $redirect);
        }

        if (isset($_SESSION['token']))
        {
            $client->setAccessToken($_SESSION['token']);
        }
        if (!$client->getAccessToken())
        {
            $state = mt_rand();
            $client->setState($state);
            $_SESSION['state'] = $state;
            $authUrl = $client->createAuthUrl();
            $htmlBody = <<<END
  <h3>Authorization Required</h3>
  <p>You need to <a href="$authUrl">authorize access</a> before proceeding.<p>
END;
        }else{

            try
            {

                $uris = explode("list=", urldecode($feed_url));
                $playlistId = $uris[self::POS_PLAYLIST_ID];

                $pageToken = "";
                if (isset($_REQUEST['pageToken']))
                {
                    $pageToken = $_REQUEST['pageToken'];
                }
                if (!empty($pageToken))
                {

                    $playlistItems = $youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', array(
                        'maxResults' => self::MAX_RESULTS,
                        'playlistId' => $playlistId,
                        'pageToken' => $pageToken
                            ));
                }else{

                    $playlistItems = $youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', array(
                        'maxResults' => self::MAX_RESULTS,
                        'playlistId' => $playlistId,
                            ));
                }
                if (empty($playlistItems)){
                    print 'No playlists found';
                }
                $htmlBody.= $this->feedToHtml($playlistItems);
                //echo $htmlBody;
            }
            catch (Google_ServiceException $e){
                $htmlBody .= sprintf('<p>A service error occurred feeds_from_playlist: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            }
            catch (Google_Exception $e){
                $htmlBody .= sprintf('<p>An client error occurred feeds_from_playlist: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
            }
        }
        echo $htmlBody;
    }

    public function refresh_token()
    {

        $scriptUri = "http://" . $_SERVER["HTTP_HOST"] . "/Index/oauth";
        require_once 'Zend/Loader.php';
        $frontController = Zend_Controller_Front::getInstance();
        $appConfig = $frontController->getParam('bootstrap')->getOptions();
        $client = new Google_Client();
        $client->setAccessType('offline'); // default: offline
        $client->setApplicationName($appConfig['applicationName']);
        $client->setClientId($appConfig['clientId']);
        $client->setClientSecret($appConfig['clientSecret']);
        $client->setDeveloperKey($appConfig['developerKey']); // API key
        $client->setRedirectUri($scriptUri);
        $redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . "/Index/oauth", FILTER_SANITIZE_URL);
        $client->setRedirectUri($redirect);
        $google_token = json_decode($_SESSION['token']);

        try
        {
            $google_token= json_decode($_SESSION['sessionToken']);
            $client->refreshToken($google_token->refresh_token);
            return true;
        }
        catch (Exception $exc)
        {
            echo $exc->getTraceAsString();
            return false;
        }

    }
}
